<template>
  <div style="width: 150vh;position: relative;margin: 0 auto;background-color: #f5f7fa;padding: 20px">
    <el-card class="hotel-details">
      <el-row :gutter="5">
        <el-col :span="16">
          <div>
            <span style="font-size: 20px;font-weight: bold;">
              {{hotelInfo.hotelName}}
            </span>
          </div>
          <div style="margin-top: 10px;color: #455873;font-size: 16px;">
            <div style="display: flex;align-items: flex-end;margin-bottom: 5px">
              <el-icon><Location /></el-icon>
              {{hotelInfo.address}}
            </div>
            <div style="display: flex;align-items: flex-end;margin-bottom: 5px">
              <el-icon><OfficeBuilding /></el-icon>
              {{hotelInfo.description}}
            </div>
          </div>
          <div>
            <img :src="hotelInfo.imgUrl" style="width: 300px;margin-top: 5px">
          </div>
        </el-col>
        <el-col :span="8">
          <div style="display: flex;flex-direction: row;justify-content: flex-end;align-items: flex-end;">
            <span style="font-size: 20px;font-weight: bold;color: #f00">
              ￥{{hotelInfo.minPrice}}
              <span style="font-size: 14px;color: #000">起</span>
            </span>
            <button class="choose-room" @click="toRoom">选择房间</button>
          </div>
          <div style="margin-top: 10px;padding-top: 10px">
            <div style="color:#007fe9;display:flex;margin-bottom:10px;">
              <span class="spanPfen">{{hotelInfo.lvcard}}分</span>
              <div v-if="hotelInfo.lvcard >= 3">棒</div>
              <div v-else>体验良好</div>
            </div>
          </div>
          <div style="margin-top: 20px;font-size: 20px;font-weight: bold;color: #ff7700">
            <span>
              联系电话：{{hotelInfo.phone}}
            </span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card style="width:102vh;margin: 10px auto;">
      <el-form label-position="top">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="入住日期">
              <el-date-picker
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="入住日期"
                  end-placeholder="退房日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  style="width:100%"
                  v-model="times"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <div class="form-group">
              <el-form-item label="房间数量">
                <el-input-number v-model="roomSearch.room" :min="1" :max="10"/>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="6">
            <div class="form-group">
              <el-form-item label="住客人数">
                <el-input-number v-model="roomSearch.person" :min="1" :max="10"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="room-card" v-for="item in roomInfoArr" :key="item.title" id="room">
      <el-row :gutter="10">
        <el-col :span="6">
          <div>
            <img :src="item.imgUrl" style="width: 150px">
          </div>
          <div>
            <span>{{item.roomType}}</span>
            <br>
            <span style="font-size: 14px">{{item.description}}</span>
          </div>
        </el-col>
        <el-col :span="18">
          <div style="border-left: #2c3e50;display: flex;align-items: center;flex-direction: column">
            <el-row :gutter="10">
              <el-col :span="12">
                <div style="font-size: 20px">
                  <el-icon v-for="n in item.perNum"><UserFilled /></el-icon>
                </div>
                <div>
                  <span style="font-size: 20px">{{item.breakfast}}</span>
                </div>
              </el-col>
              <el-col :span="12" style="text-align: center;">
                <div style="width: 323px;display: flex;flex-direction: column;justify-content: space-between;align-items: end;">
                  <span style="font-size: 20px;font-weight: 600;color: #0086f6;line-height: 50px;display: inline-block">
                    ￥{{item.pricePerNight}}
                  </span>
                  <div>
                    <button class="order" v-if="item.num>0" @click="roomOrder(item.id)">预定</button>
                    <button class="order" style="background-color: #a1a1a1;" v-else-if="item.num===0" :disabled="item.num===0">售完</button>
                  </div>
                  <div>
                    <span style="color: #f00;" v-if="item.num<=5 && item.num>0">
                      房间仅剩{{item.num}}间
                    </span>
                    <span style="color: #f00;" v-else-if="item.num===0">
                      售罄
                    </span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>

<!-- 房间预定弹窗 -->
  <el-dialog title="酒店房间预定" v-model="roomOrderDialogVisible" style="padding:40px;">
    <el-card>
      <div>
        <span style="font-size: 20px;font-weight: bold;">
          {{hotelInfo.hotelName}}
        </span>
      </div>
      <div style="margin-top: 10px;color: #455873;font-size: 16px;">
        <div style="display: flex;align-items: flex-end;margin-bottom: 5px">
          <el-icon><Location /></el-icon>
          {{hotelInfo.address}}
        </div>
        <div style="display: flex;align-items: flex-end;margin-bottom: 5px">
          {{roomInfo.roomType}}
        </div>
        <div style="display: flex;align-items: flex-end;margin-bottom: 5px">
          <el-icon><UserFilled /></el-icon>{{roomInfo.perNum}}人
          <el-icon style="margin-left: 20px"><ChatLineSquare /></el-icon>{{roomInfo.description}}
        </div>
      </div>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-form label-position="top">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="入住日期">
              <el-date-picker
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="入住日期"
                  end-placeholder="退房日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  style="width:100%"
                  v-model="times"
                  @change="calculateLengthOfStay"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="form-group">
              <el-form-item label="房间数量">
                <el-input-number v-model="roomSearch.room" :min="1" :max="10"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <span style="font-size: 20px;font-weight: bold;margin-top: 10px">
          住客资料
        </span>
        <div style="margin-top: 10px;" v-for="(room,index) in roomSearch.room" :key="index">
          <span style="font-size: 16px;font-weight: 700;" v-if="roomSearch.room > 1 || index>0">
            房间{{index+1}}
          </span>
          <el-form-item label="住客姓名">
            <el-autocomplete style="width: 50%;"
                      placeholder="请输入住客姓名"
                      v-model="guestNameArr[index]"
                      :fetch-suggestions="fetchGuestName"
                      @select="selectSuggestion"
                      trigger-on-focus
                      required
            ></el-autocomplete>

          </el-form-item>
        </div>
        <div>
          <el-form-item label="联系电话">
            <el-input style="width: 50%;" placeholder="请输入联系电话" v-model="roomOrderForm.phone" required></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="支付方式">
            <el-select style="width: 150px" v-model="roomOrderForm.payMethod">
              <el-option label="微信" value="10"></el-option>
              <el-option label="支付宝" value="20"></el-option>
            </el-select>
          </el-form-item>
          <span style="font-size: 20px;font-weight: 700">
            支付金额：<span style="color: #f00">￥{{roomInfo.pricePerNight * roomSearch.room * lengthOfStay}}</span>
          </span>
        </div>
      </el-form>
    </el-card>
    <template #footer>
      <el-button >取消</el-button>
      <el-button type="primary" @click="payment">支付</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref, watch} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";
import response from "core-js/internals/is-forced";

// 酒店房间订单弹窗显示隐藏
const roomOrderDialogVisible = ref(false);


//定义一个对象用来存储对应的酒店信息
const hotelInfo = ref({
  hotelId:'',
  hotelName:'',
  minPrice:'',
  imgUrl:'',
  address:'',
  lvcard:'',
  description:'',
  phone:''
});
//获取URL中的查询字符串参数
const hotelId = new URLSearchParams(window.location.search).get('hotelId');
// 在组件挂载时读取 Local Storage 中的表单数据
onMounted(() => {
    getHotelInfo();
});
//根据酒店id获取酒店信息
const getHotelInfo = ()=>{
  axios.get(BASE_URL+"/v1/hotel/select?id="+hotelId)
      .then(response=>{
    if (response.data.code===2000){
      hotelInfo.value = response.data.data[0];

      //获取当前酒店房间的最低价
      axios.get(BASE_URL+'/v1/room/selectMinPrice/'+hotelId)
          .then((response)=>{
            if(response.data.code===2000){
              hotelInfo.value.minPrice = response.data.data[0].minPrice;
            }else{
              ElMessage.error(response.data.msg);
            }
          })
      //获取当前酒店房间的信息
      axios.get(BASE_URL+'/v1/room/select?hotelId='+hotelId)
          .then((response)=>{
            if (response.data.code===2000){
              roomInfoArr.value = response.data.data;
            }else{
              ElMessage.error(response.data.msg);
            }
          })
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//定义一个数组用来保存酒店内的房间
const roomInfoArr = ref([])


//定义一个点击事件实现点击选择房间按钮时,页面直接滑到房间信息处
const toRoom = ()=>{
  const a = ref(document.getElementById("room"));
  if (a){
    a.value.scrollIntoView({behavior: "smooth"});
  }
}

const roomSearch = ref({
  room:'',
  person:''
});
// 定义一个数组用来放入住日期和退房日期
const times = ref([]);
// 在组件挂载时读取 Local Storage 中的表单数据
onMounted(() => {
  const storedForm = localStorage.getItem('roomSearch');
  if (storedForm) {
    roomSearch.value = JSON.parse(storedForm);
    console.log(storedForm)
    times.value[0] = roomSearch.value.checkinDate;
    times.value[1] = roomSearch.value.checkoutDate;
  }
});

// 定义一个根据房间id获取的房间信息
const roomInfo = ref({});

// 定义一个方法实现预定酒店房间按钮的点击事件
const roomOrder = (id)=>{
  getPassenger();
  roomOrderDialogVisible.value = true;
  //todo 点击预定按钮,将订单添加到订单表中,并设置订单状态为未支付
  roomSearch.value.checkinDate = times.value[0];
  roomSearch.value.checkoutDate = times.value[1];
  roomOrderForm.value.payMethod = '微信';
  // guestNameArr.value = guestName.value;
  roomOrderForm.value.guestName = guestName.value[0];
  // 将表单数据存储到 Local Storage 中
  localStorage.setItem('roomOrderForm', JSON.stringify(roomSearch.value));
  axios.get(BASE_URL+'/v1/room/select?id='+id)
      .then((response)=>{
        if (response.data.code===2000){
          roomInfo.value = response.data.data[0];
          roomOrderDialogVisible.value=true;
          const storedForm = localStorage.getItem('roomSearch');
          if (storedForm) {
            roomSearch.value = JSON.parse(storedForm);
            times.value[0] = roomSearch.value.checkinDate;
            times.value[1] = roomSearch.value.checkoutDate;
          }

          const date1 = new Date(roomSearch.value.checkinDate);
          const date2 = new Date(roomSearch.value.checkoutDate);
          const timeDifference = date2 - date1; // 毫秒差
          lengthOfStay.value = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));

        }else{
          ElMessage.error(response.data.msg);
        }
      })
}

//定义一个数组存储住客姓名
const guestNameArr = ref(Array.from({ length: roomSearch.value.room }, () => ''));

//定义对象存储订单表单的数据
const roomOrderForm = ref({
  guestName:'',
  phone:'',
  payMethod:'',
})

// 定义一个方法计算入住时长
const lengthOfStay = ref(0);

const calculateLengthOfStay = ()=>{
  if (!roomSearch.value.checkinDate.value || !roomSearch.value.checkoutDate.value) {
    const checkinDate = times.value[0];
    const checkoutDate = times.value[1];

    const date1 = new Date(checkinDate);
    const date2 = new Date(checkoutDate);
    const timeDifference = date2 - date1; // 毫秒差
    lengthOfStay.value = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
    return lengthOfStay.value; // 转换为天
  }
}

const guestName = ref([]);
// 获取建议列表
const fetchGuestName = (queryString, cb) => {
  const results = queryString ? guestName.value.filter(suggestion => suggestion.includes(queryString)) : guestName.value
  // 调用回调函数传递建议列表
  cb(results.map(suggestion => ({ value: suggestion })))
}
// 当用户选择了一个建议
const selectSuggestion = (suggestion,index) => {
  roomOrderForm.value.guestName[index] = suggestion.value;
}
const userId = getUser().id;
// 定义一个数组存储旅客信息
const passengerInfo = ref([]);
// 定义一个方法获取当前用户所绑定的旅客信息
const getPassenger = ()=>{
  axios.get(BASE_URL+'/v1/passenger/select/'+userId)
      .then((response)=>{
        if (response.data.code===2000){
          passengerInfo.value = response.data.data;
          for (let i = 0; i < passengerInfo.value.length; i++) {
            guestName.value[i] = passengerInfo.value[i].name;
          }
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}

//定义一个方法实现订单支付功能
const payment = ()=>{
  roomOrderForm.value.guestName=guestNameArr.value.join(',');
  roomOrderForm.value.hotelId=hotelId;
  roomOrderForm.value.roomId=roomInfo.value.id;
  roomOrderForm.value.checkinDate=roomSearch.value.checkinDate;
  roomOrderForm.value.checkoutDate=roomSearch.value.checkoutDate;
  roomOrderForm.value.roomNum=roomSearch.value.room;
  roomOrderForm.value.totalPrice=roomInfo.value.pricePerNight * roomSearch.value.room * lengthOfStay.value;
  roomOrderForm.value.userId=getUser().id;
  console.log(roomOrderForm.value);
  console.log(guestNameArr.value)
  console.log(guestNameArr.value.join(','))
  let data = qs.stringify(roomOrderForm.value)
  //提交订单会将订单状态改为已支付
  axios.post(BASE_URL+'/v1/order/roomOrder/insert',data)
      .then((response)=>{
        if (response.data.code===2000){
          ElMessage.success("预定成功");
          roomOrderDialogVisible.value = false;
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
</script>

<style scoped>
.hotel-details {
  width: 100vh;
  margin: 0 auto;
  padding: 10px;
}

.choose-room {
  width: 100px;
  height: 40px;
  background-color: #287dfa;
  color: #fff;
  border-radius: 3px;
  border: none;
  margin-left: 10px;
  font-weight: bold;
  font-size: 17px;
}
.spanPfen{
  display: inline-block;
  width: 40px;
  height: 20px;
  background: #007fe9;
  color: #fff;
  text-align: center;
  line-height: 13px;
  border-radius: 3px;
  margin-right: 10px;
  padding-top: 8px;
}
.room-card {
  width: 102vh;
  height: 200px;
  margin: 10px auto;
}
.order{
  height: 38px;
  background-color: #ff9500;
  font-size: 16px;
  line-height: 38px;
  border: none;
  color: #fff;
  margin-bottom: 10px;
  padding: 0 24px;
}

</style>